package org.testfire.realm.converters;

import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.log4j.Logger;
import org.testfire.realm.util.UtilityBean;

/**
 * Convert an Enum value to a string value, and back.
 * @author Geoff M. Granum
 * @version 1.0
 */
public class EnumConverter implements Converter
{

    public EnumConverter()
    {
    }

    /**
     * Takes a string value and returns the Enum type to which it corresponds.
     * @param context Passed by the Application Server
     * @param comp The component which this Converter is attatched to, which is backed by an Enum type.
     * @param value The string value which matches that of an Enum.
     * @return The Enum value which matches the String which was passed.
     * @throws ConverterException On failure to match the string to an Enum type.
     */
    public Object getAsObject( FacesContext context, UIComponent comp,
        String value ) throws ConverterException
    {
        Class enumType = comp.getValueExpression( "value" ).getType( context.getELContext() );
        Enum o = null;
        try
        {
            o = Enum.valueOf( enumType, value );
        }
        catch ( Exception ex )
        {
            Logger.getLogger(EnumConverter.class).error("", ex );
            throw new ConverterException( ex );
        }
        if ( o == null )
        {
            Map map = UtilityBean.getEnumMap( enumType );
            for ( Object obj : map.keySet() )
            {
                if ( map.get( obj ).equals( value ) )
                {
                    o = (Enum)obj;
                    break;
                }
            }
        }
        return o;
    }

    /**
     * Takes an Enum object value and returns the String value to which it corresponds
     * @param context The context, passed by the Application server.
     * @param component comp The component which this Converter is attatched to, which is backed by an Enum type.
     * @param object The Enum type to get the String value of.
     * @return A string, as found from the toString() method of the Enum type.
     * @throws ConverterException On failure to convert.
     */
    public String getAsString( FacesContext context, UIComponent component,
        Object object ) throws ConverterException
    {
        if ( object == null )
        {
            return null;
        }
        if ( object instanceof Enum )
        {
            return ((Enum)object).toString();
        }
        return object.toString();
    }


}
